package net.wendal.luat.air720.module;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.http.Request;
import org.nutz.http.Sender;
import org.nutz.http.Request.METHOD;
import org.nutz.http.Response;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Streams;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;

@IocBean
public class CgiProxyModule {

    @Ok("void")
    @Fail("http:500")
    @At({"/login", "/xml_action"})
    public void proxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String url = "http://192.168.0.1" + req.getRequestURI() + "?" + req.getQueryString();
        //System.out.println("URL=" + url);
        Request request = Request.create(url, METHOD.valueOf(req.getMethod()));
        Enumeration<String> en = req.getHeaderNames();
        while (en.hasMoreElements()) {
            String name = en.nextElement();
            String value = req.getHeader(name);
            //System.out.println("REQ Header " + name + "=" + value);
            request.header(name, value);
            
        }
        request.setInputStream(req.getInputStream());
        Response response = Sender.create(request).send();
        resp.setStatus(response.getStatus());
        for (String name : response.getHeader().keys()) {
            if (name == null)
                continue;
            String value = response.getHeader().get(name);
            resp.setHeader(name, value);
            //System.out.println("RESP Header " + name + "=" + value);
        }
        Streams.writeAndClose(resp.getOutputStream(), response.getStream());
    }
}
